package com.leo.erp.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.erp.dao.DepotHeadMapper;
import com.leo.erp.dao.DepotItemMapper;
import com.leo.erp.dao.DepotMapper;
import com.leo.erp.dto.DepotExecution;
import com.leo.erp.entity.Depot;
import com.leo.erp.entity.DepotHead;
import com.leo.erp.entity.DepotItem;
import com.leo.erp.entity.User;
import com.leo.erp.enums.DepotHeadStateEnum;
import com.leo.erp.enums.DepotItemStateEnum;
import com.leo.erp.enums.DepotStateEnum;
import com.leo.erp.service.DepotService;
import com.leo.erp.service.LogService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.StringUtil;

@Service
public class DepotServiceImpl implements DepotService{
	@Autowired
	private DepotMapper depotMapper;
	@Autowired
	private LogService logService;
	@Autowired
	private DepotHeadMapper depotHeadMapper;
	@Autowired
	private DepotItemMapper depotItemMapper;

	@Override
	public DepotExecution findUserDepot() {
		DepotExecution de = new DepotExecution();
		QueryWrapper<Depot> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("type", 0);
		queryWrapper.ne("deleteFlag", "1");
		queryWrapper.orderByAsc("sort");
		try {
			List<Depot> list = depotMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				de.setState(DepotStateEnum.SUCCESS.getState());
				de.setDepotList(list);
			}else {
				de.setState(DepotStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return de;
	}

	@Override
	public DepotExecution checkIsNameExist(int id, String name) {
		DepotExecution de = new DepotExecution();
		QueryWrapper<Depot> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("depotId", id);
		queryWrapper.eq("depotName", name);
		queryWrapper.ne("deleteFlag", "1");
		try {
			List<Depot> list = depotMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				de.setState(DepotStateEnum.SUCCESS.getState());
			}else {
				de.setState(DepotStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return de;
	}

	@Override
	public DepotExecution insertDepot(String beanJson, HttpServletRequest request) {
		DepotExecution de = new DepotExecution();
		Depot depot = JSONObject.parseObject(beanJson, Depot.class);
		//session
		User user = (User) request.getSession().getAttribute("user");
		depot.setTenantId(user.getUserId());
		depot.setPrincipal(user.getUserId());
		try {
			int effectedNum = depotMapper.insert(depot);
			if(effectedNum > 0) {
				logService.insertLog("仓库", "新增" + depot.getDepotName(), request);
				de.setState(DepotStateEnum.SUCCESS.getState());
			}else {
				de.setState(DepotStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return de;
	}

	@Override
	public DepotExecution getAllList() {
		DepotExecution de = new DepotExecution();
		QueryWrapper<Depot> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("deleteFlag", "1");
		queryWrapper.orderByAsc("sort");
		try {
			List<Depot> list = depotMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				de.setState(DepotStateEnum.SUCCESS.getState());
				de.setDepotList(list);
			}else {
				de.setState(DepotStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return de;
	}

	/**
	 * 正常删除，要考虑数据完整性，进行完整性校验
	 */
	@Override
	@Transactional
	public DepotExecution batchDeleteDepotByIdsNormal(String ids) {
		DepotExecution de = new DepotExecution();
		/**
         * 校验
         * 1、单据主表	tb_depot_head
         * 2、单据子表	tb_depot_item
         * 是否有相关数据
         * */
		if(StringUtil.isEmpty(ids)) {
			de.setState(DepotStateEnum.OFFLINE.getState());
			return de;
		}
		
		List<Long> idList = StringUtil.strToLongList(ids);//转换成数组
		
		/**
         * 校验单据子表	tb_depot_item
         * */
		try {
			QueryWrapper<DepotItem> queryDepotItem = new QueryWrapper<>();
			queryDepotItem.in("depotId", idList);
			List<DepotItem> depotItemList = depotItemMapper.selectList(queryDepotItem);
			if(depotItemList.size() > 0) {
				//有数据,可以执行强制删除
				de.setState(DepotItemStateEnum.DELETE.getState());
				return de;
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		/**
         * 校验单据子表	tb_depot_head
         * */
		try {
			QueryWrapper<DepotHead> queryDepotHead = new QueryWrapper<>();
			queryDepotHead.in("organId", idList);
			List<DepotHead> depotHeadList = depotHeadMapper.selectList(queryDepotHead);
			if(depotHeadList.size() > 0) {
				//有数据,可以执行强制删除
				de.setState(DepotHeadStateEnum.DELETE.getState());
				return de;
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		/**
         * 校验通过执行删除操作
         * */
		int effectedNum = batchDeleteDepotByIds(ids);
		if(effectedNum > 0) {
			de.setState(DepotStateEnum.SUCCESS.getState());
		}else {
			de.setState(DepotStateEnum.OFFLINE.getState());
		}
		
		return de;
	}

	@Transactional
	public int batchDeleteDepotByIds(String ids) {
		StringBuffer sb = new StringBuffer();
		List<Long> idList = StringUtil.strToLongList(ids);//转换成数组
		List<Depot> list = null;
		int result = 0;
		try {
			QueryWrapper<Depot> queryWrapper = new QueryWrapper<>();
			queryWrapper.in("depotId", idList);
			list = depotMapper.selectList(queryWrapper);
			for(Depot depot : list) {
				sb.append("[").append(depot.getDepotName()).append("]");
			}
			//session
			HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
			User user = (User) request.getSession().getAttribute("user");
			Depot depot = new Depot();
			depot.setTenantId(user.getUserId());
			depot.setDeleteFlag("1");
			//更新条件
			UpdateWrapper<Depot> updateWrapper = new UpdateWrapper<>();
			updateWrapper.in("depotId", idList);
			int effectedNum = depotMapper.update(depot, updateWrapper);
			if(effectedNum > 0) {
				logService.insertLog("仓库", "删除:" + sb.toString(), ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
				result = 1;
			}else {
				result = 0;
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	@Transactional
	public DepotExecution updateDepotIsDefault(int isDefault, int depotId) {
		
		DepotExecution de = new DepotExecution();
		//先查询原本信息
		Depot depot = depotMapper.selectById(depotId);;
		depot.setIsDefault(isDefault);
		//session
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		User user = (User) request.getSession().getAttribute("user");
		depot.setTenantId(user.getUserId());
		UpdateWrapper<Depot> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("depotId", depotId);
		try {
			int effectedNum = depotMapper.update(depot, updateWrapper);
			if(effectedNum > 0) {
				logService.insertLog("仓库", "修改:" + depotId, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
				de.setState(DepotStateEnum.SUCCESS.getState());
			}else {
				de.setState(DepotStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return de;
	}

	@Override
	@Transactional
	public DepotExecution updateDepot(String beanJson, int depotId, HttpServletRequest request) {
		//查询是否默认
		Depot depotM = depotMapper.selectById(depotId);
		DepotExecution de = new DepotExecution();
		Depot depot = JSONObject.parseObject(beanJson, Depot.class);
		depot.setDepotId(depotId);
		depot.setIsDefault(depotM.getIsDefault());
		//session
		User user = (User) request.getSession().getAttribute("user");
		depot.setTenantId(user.getUserId());
		
		try {
			int effectedNum = depotMapper.updateById(depot);
			if(effectedNum > 0) {
				logService.insertLog("仓库", "修改:" + depot.getDepotName().toString(), request);
				de.setState(DepotStateEnum.SUCCESS.getState());
			}else {
				de.setState(DepotStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return de;
	}

	@Override
	@Transactional
	public DepotExecution select(String name, Integer type, String remark, int currentPage, int pageSize) {
		DepotExecution de =new DepotExecution();
		QueryWrapper<Depot> queryWrapper = new QueryWrapper<>();
		
		//判断
		if(name != null && name != "") {
			queryWrapper.like("depotName", name);
		}
		if(type != null) {
			queryWrapper.like("type", type);
		}
		if(remark != null && remark != "") {
			queryWrapper.like("remark", remark);
		}
		queryWrapper.ne("deleteFlag", "1");
		
		Page<Depot> page = new Page<>(currentPage, pageSize);//分页查询
		IPage<Map<String, Object>> iPage = depotMapper.selectMapsPage(page, queryWrapper);
		if(iPage.getRecords().size() > 0) {
			de.setState(DepotStateEnum.SUCCESS.getState());
			de.setPages(page.getPages());//总页数
			de.setTotal(iPage.getTotal());//总记录数
			de.setDepotPageList(iPage.getRecords());
		}else{
			de.setState(DepotStateEnum.OFFLINE.getState());
		}
		
		return de;
	}
	
	
}
